package com.hxzy.controller.admin.dicttype;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.resp.PageResp;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.admin.dicttype.req.DictTypeAddReq;
import com.hxzy.controller.admin.dicttype.req.DictTypeEditReq;
import com.hxzy.controller.admin.dicttype.req.DictTypeReq;
import com.hxzy.controller.admin.dicttype.resp.DictTypeResp;
import com.hxzy.controller.admin.mapstruct.DictTypeConvert;
import com.hxzy.entity.SysDictData;
import com.hxzy.entity.SysDictType;
import com.hxzy.service.SysDictTypeService;
import com.hxzy.util.DictCacheUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Desc 描述
 * @Author: admin
 * @Date: 2023/07/03/14:41
 */
@Api(tags = "管理后台-数据字典")
@RestController
@RequestMapping(value = "/api/dicttype")
public class DictTypeController {

    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Autowired
    private DictCacheUtil  dictCacheUtil;

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "data")
    public R<PageResp<DictTypeResp>> search( @Valid DictTypeReq req){
        PageInfo<SysDictType> pageInfo=this.sysDictTypeService.search(req);

        PageResp<DictTypeResp> resp=new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setRows(DictTypeConvert.INSTANCE.convert(pageInfo.getList()));
        return R.okHasData(resp);
    }


    @ApiOperation(value = "excel下载")
    @PostMapping(value = "/download")
    public void download(HttpServletResponse response,@RequestBody  DictTypeReq req) throws IOException {

        List<SysDictType> arrList=this.sysDictTypeService.download(req);
        List<DictTypeResp> convert = DictTypeConvert.INSTANCE.convert(arrList);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("data", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DictTypeResp.class).sheet("数据").doWrite(convert);
    }


    @ApiOperation(value = "所有数据")
    @GetMapping(value = "/dataAll")
    public R<List<Map<String,Object>>> searchAll(){
        List<Map<String,Object>> list=this.sysDictTypeService.dataAll();
        return R.okHasData(list);
    }

    @ApiOperation(value = "新增")
    @PostMapping
    public R add(@RequestBody @Valid DictTypeAddReq req){
        SysDictType entity = DictTypeConvert.INSTANCE.convert(req);
        boolean save = this.sysDictTypeService.save(entity);
        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<DictTypeResp> findById(@PathVariable(value = "id") Long id){
        if(Objects.isNull(id) || id.intValue()<=0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }
        SysDictType db = this.sysDictTypeService.getById(id);
        if(Objects.isNull(db)){
            return R.build(AckCode.DATA_NOT_FOUND);
        }

        return R.okHasData( DictTypeConvert.INSTANCE.convert(db));
    }

    @ApiOperation(value = "修改")
    @PutMapping
    public R update(@RequestBody @Valid DictTypeEditReq req){
        if( req.getId().intValue()<=0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }
        //这里要做事务操作，因为会有多个表的操作
        boolean save=this.sysDictTypeService.edit(req);

        return save? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "刷新缓存")
    @PostMapping(value = "/refresh")
    public R freshRedisCache(){
        this.dictCacheUtil.removeAllRedisDictData();
        this.dictCacheUtil.loadAllDictDataToRedis();
        return R.ok();
    }

    @ApiOperation(value = "逻辑删除")
    @DeleteMapping
    public R delete(Long[] ids){
        if(Objects.isNull(ids) || ids.length==0){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        //1、查询禁用操作的dictType值
        LambdaQueryWrapper<SysDictType> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(SysDictType::getId,ids);
        queryWrapper.select(SysDictType::getDictType);
        List<Map<String, Object>> mapList = this.sysDictTypeService.listMaps(queryWrapper);


        //2、更新数据库的缓存
        boolean result=this.sysDictTypeService.delete(ids);

        //3、更新redis的缓存
        for(Map<String,Object> map: mapList){
            String dictType= map.get("dict_type").toString();
            this.dictCacheUtil.removeByDictType(dictType);
        }

        return result? R.ok(): R.build(AckCode.DATABASE_ERROR);
    }
}
